package com.haoxuer.discover.plug.data.service.impl;

import com.haoxuer.discover.plug.api.ProxyPlugin;
import com.haoxuer.discover.plug.data.service.ProxyService;
import com.haoxuer.discover.rest.base.ResponseObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;


@Service("proxyServiceImpl")
public class ProxyServiceImpl implements ProxyService {

  private ExecutorService executorService;

  public ProxyServiceImpl() {

    executorService = new ThreadPoolExecutor(1, 50,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());

  }

  @Resource
  private List<ProxyPlugin> plugins = new ArrayList<ProxyPlugin>();

  public List<ProxyPlugin> getPlugins() {
    Collections.sort(plugins);
    return plugins;
  }

  public List<ProxyPlugin> getPlugins(String catalog, final boolean isEnabled) {
    List<ProxyPlugin> result = plugins.stream().filter(item -> item.catalog().equals(catalog))
        .filter(item -> item.getIsEnabled()).collect(Collectors.toList());
    Collections.sort(result);
    Collections.sort(result);
    return result;
  }

  @Override
  public ResponseObject handleSingle(String catalog, Map<String, String> params) {
    ResponseObject result = new ResponseObject();
    List<ProxyPlugin> plugins = getPlugins(catalog, true);
    if (plugins == null || plugins.isEmpty()) {
      result.setCode(501);
      result.setMsg("没有可用的服务");
      return result;
    }
    result = plugins.get(0).handle(params);
    return result;
  }

  @Override
  public ResponseObject handleSerial(String catalog, Map<String, String> params) {
    ResponseObject result = new ResponseObject();
    List<ProxyPlugin> plugins = getPlugins(catalog, true);
    if (plugins != null) {
      for (ProxyPlugin plugin : plugins) {
        plugin.handle(params);
      }
    }
    return result;
  }

  @Override
  public ResponseObject handleParallel(String catalog, Map<String, String> params) {
    ResponseObject result = new ResponseObject();
    List<ProxyPlugin> plugins = getPlugins(catalog, true);
    if (plugins != null) {
      for (ProxyPlugin plugin : plugins) {
        HandleProxyThread proxy = new HandleProxyThread(plugin, params);
        executorService.execute(proxy);
      }
    }
    return result;
  }
}
